#include <event2/event.h>
#include <event2/http.h>
#include <event2/buffer.h>
#include <event2/util.h>
#include <iostream>
#include <signal.h>
#include <sys/resource.h>

static int count = 0;
static struct event_base* main_base = nullptr;

// 信号处理函数，优雅关闭服务器
static void signal_handler(int sig) {
    std::cout << "Received signal " << sig << ", shutting down gracefully...\n";
    if (main_base) {
        event_base_loopexit(main_base, nullptr);
    }
}

// 优化的HTTP请求处理函数
static void http_request_handler(struct evhttp_request* req, void* arg) {
    // 检查请求是否有效
    if (!req) {
        std::cerr << "Invalid request received\n";
        return;
    }
    printf("%d\n", count++);
    // 获取输出头部并设置连接管理
    struct evkeyvalq* headers = evhttp_request_get_output_headers(req);
    evhttp_add_header(headers, "Content-Type", "text/plain; charset=utf-8");
    //evhttp_add_header(headers, "Connection", "close");  // 强制短连接
    evhttp_add_header(headers, "Server", "libevent-http-server");
    
    // 创建响应缓冲区
    struct evbuffer* buf = evbuffer_new();
    if (!buf) {
        std::cerr << "Failed to create response buffer\n";
        evhttp_send_error(req, HTTP_SERVUNAVAIL, "Internal Server Error");
        return;
    }
    
    // 添加响应内容
    evbuffer_add_printf(buf, "Hello, World! This is a response from libevent HTTP server.\n");
    evbuffer_add_printf(buf, "Request handled at: %ld\n", time(nullptr));
    
    // 发送响应
    evhttp_send_reply(req, 200, "OK", buf);
    
    // 释放资源
    evbuffer_free(buf);
}

// 优化系统资源限制
void optimize_system_limits() {
    struct rlimit rl;
    
    // 增加文件描述符限制
    rl.rlim_cur = rl.rlim_max = 65536;
    if (setrlimit(RLIMIT_NOFILE, &rl) == -1) {
        std::cerr << "Warning: Could not set file descriptor limit to 65536\n";
    }
    
    std::cout << "System limits optimized\n";
}

// 监控函数
void print_server_status() {
    static int request_count = 0;
    request_count++;
    
    if (request_count % 100 == 0) {
        std::cout << "Processed " << request_count << " requests\n";
    }
}

int main() {
    std::cout << "Starting optimized libevent HTTP server...\n";
    
    // 优化系统限制
    optimize_system_limits();
    
    // 设置信号处理
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);
    signal(SIGPIPE, SIG_IGN);  // 忽略SIGPIPE信号，防止程序崩溃
    
    // 创建事件基础框架
    main_base = event_base_new();
    if (!main_base) {
        std::cerr << "Could not initialize libevent!\n";
        return 1;
    }
    
    std::cout << "Using libevent backend: " << event_base_get_method(main_base) << std::endl;
    
    // 创建HTTP服务器
    struct evhttp* http_server = evhttp_new(main_base);
    if (!http_server) {
        std::cerr << "Could not create new evhttp.\n";
        event_base_free(main_base);
        return 1;
    }
    
    // 设置服务器参数
    evhttp_set_timeout(http_server, 2);                    // 30秒超时
    evhttp_set_max_body_size(http_server, 1024 * 1024);     // 限制请求体1MB
    evhttp_set_max_headers_size(http_server, 8192);         // 限制头部8KB
    
    // 绑定地址和端口
    if (evhttp_bind_socket(http_server, "0.0.0.0", 28080) != 0) {
        std::cerr << "Could not bind to port 28080.\n";
        evhttp_free(http_server);
        event_base_free(main_base);
        return 1;
    }
    
    // 设置请求处理函数
    evhttp_set_gencb(http_server, http_request_handler, NULL);
    
    std::cout << "HTTP server started on port 28080.\n";
    std::cout << "Ready to handle requests...\n";
    
    // 事件循环
    event_base_dispatch(main_base);
    
    // 优雅关闭
    std::cout << "Shutting down server...\n";
    evhttp_free(http_server);
    event_base_free(main_base);
    
    std::cout << "Server shutdown complete.\n";
    return 0;
}